#!/bin/sh
cd `pwd`

STR=`ps -ef | grep java | grep "com.perfma.xtest.WMain" | awk  -F ' '  '{print $2}'`
if [ ! -z "$STR" ]; then
    kill -9 $STR > /dev/null 2>&1
    sleep 2
else
  echo "没有Java进程"
fi

APP_HOME=`readlink -f $0`
APP_HOME=`dirname $APP_HOME`
APP_HOME=`dirname $APP_HOME`

export APP_HOME

echo "APP_HOME:$APP_HOME"

DORAEMON_VERSION="r2.0.1"
# 判断 doraemon 的动态库是否存在，不存在则报错
DORAEMON_AGENT="${APP_HOME}/dlibs/libperfma_doraemon-${DORAEMON_VERSION}-linux-x64.so"
if [ ! -e ${DORAEMON_AGENT} ]; then
        echo "ERROR: can not find the ${DORAEMON_AGENT}"
        exit 1
fi

if [ ! -e ${APP_HOME}/jre ]; then
    if [ ! -e ${APP_HOME}/jre.tar.gz ]; then
        echo "WARN: can not find the jre.tar.gz file under ${APP_HOME}"
        echo "WARN: start find the jre.zip file under ${APP_HOME}"

        if [ ! -e ${APP_HOME}/jre.zip ]; then
            echo "ERROR: can not find the jre.tar.gz file under ${APP_HOME}"
            exit 1
        else
            unzip ${APP_HOME}/jre.zip -d ${APP_HOME}/ > /dev/null
            rm ${APP_HOME}/jre.zip
        fi
    else
        unzip ${APP_HOME}/jre.tar.gz -d ${APP_HOME}/ > /dev/null
        rm ${APP_HOME}/jre.tar.gz
    fi
fi

if [ ! -e ${APP_HOME}/jre ]; then
    echo "ERROR: can not find jre under ${APP_HOME}..."
    exit 1
fi

JAVA_HOME=${APP_HOME}/jre
export JAVA_HOME

#DEBUG_OPTS="-Xdebug -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n"

DIR_LOG=${APP_HOME}/../logs/xtest

if [ ! -e $DIR_LOG ] ; then
    mkdir -p $DIR_LOG
fi

JVM_OPTS="-Xmx640M -Xms640M -Xmn192M -XX:MaxMetaspaceSize=128M -XX:MetaspaceSize=128M -XX:+UseConcMarkSweepGC -XX:+UseCMSInitiatingOccupancyOnly \
-XX:CMSInitiatingOccupancyFraction=70 -XX:+ExplicitGCInvokesConcurrentAndUnloadsClasses -XX:+CMSClassUnloadingEnabled -XX:+ParallelRefProcEnabled \
-XX:+CMSScavengeBeforeRemark -XX:ErrorFile=${DIR_LOG}/hs_err_pid%p.log -Xloggc:${DIR_LOG}/gc.log -XX:+PrintGCDetails -XX:+PrintGCDateStamps -XX:-OmitStackTraceInFastThrow"

FILE_STDOUT_LOG=$DIR_LOG/stdout.log
FILE_STDERR_LOG=$DIR_LOG/stderr.log

nohup ${JAVA_HOME}/bin/java ${DEBUG_OPTS} -agentpath:${DORAEMON_AGENT} ${JVM_OPTS} -cp "${APP_HOME}/lib/*" \
-Djava.security.egd=file:/dev/./urandom \
-Dperfma.config.dir=${APP_HOME}/config \
-DPERFMA_CLUSTER_NAME=perfma_xtest \
-Dlog.root=$DIR_LOG \
-Dapp.path=${APP_HOME} \
com.perfma.xtest.WMain > ${FILE_STDOUT_LOG} 2>${FILE_STDERR_LOG} &
